package net.xdclass.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.LoginUser;

import java.util.Date;

/**
 * jwt工具类
 *
 * @author JiangZhou
 * @date 2023/5/2 15:39
 */
@Slf4j
public class JWTUtil {

    /**
     * token的过期时间
     */
    private static final long EXPIRE = 1000*60*60*24*70;

    /**
     * 签名
     */
    private static final String SECRET = "xdclass.net";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "xdclass1024sp";

    /**
     * sujectg
     */
    private static final String SUBJECT = "xdclass";

    public static String generateToken(LoginUser loginUser) {
        if (loginUser == null) {
            throw  new NullPointerException("login对象为空");
        }
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", loginUser.getHead_img())
                .claim("id", loginUser.getId())
                .claim("name", loginUser.getName())
                .claim("mail", loginUser.getMail())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREFIX+token;
        return token;
    }

    /**
     * @Description: 校验token
     * @Author: jz
     * @Date: 2023/5/2 15:53
     * @Param:
     * @Return:
     */
    public static Claims checkJwt(String token) {
        try {
            Claims claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claimsJws;
        } catch (Exception e) {
            log.info("token校验失败");
            return null;
        }
    }
}
